package com.jp.knowledge.my.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.JoinOrgnazitionAcitivity;
import com.jp.knowledge.activity.LoginActivity;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.activity.VipBuyActivity;
import com.jp.knowledge.my.adapter.VipInfoAdapter;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.my.model.VipInfoModel;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.JpDiver;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/6/16.
 */

public class VipFragment extends Fragment {

	private Context mContext;
	private View mView;

	@ViewInject(R.id.vip_level)
	private TextView vipLevel;
	@ViewInject(R.id.vip_desc)
	private TextView vipDesc;
	@ViewInject(R.id.vip_time)
	private TextView vipTime;
	@ViewInject(R.id.vip_title)
	private LinearLayout vipTitle;
	@ViewInject(R.id.vip_rv)
	private RecyclerView vipRv;
	@ViewInject(R.id.vip_content_view)
	private LinearLayout contentView;

	private int type;
	private String companyId;
	private OrganizaModel organizaModel;

	private VipInfoAdapter adapter;
	private String cachePath;
	private int screenWidth;
	private VipInfoModel vipInfoModel;
	private FileCacheManager cacheManager;
	private JpApplication jpApplication;
	private CommDialog upgradeDialog;
	private boolean shouldReloadData;

	public static VipFragment newInstance(int type, OrganizaModel organizaModel){
		VipFragment fragment = new VipFragment();
		Bundle bundle = new Bundle();
		bundle.putInt("type", type);
		bundle.putSerializable("organizaModel", organizaModel);
		fragment.setArguments(bundle);
		return fragment;
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(mContext != null)
			return;
		mContext = getContext();
		jpApplication = (JpApplication) getActivity().getApplication();
		mView = View.inflate(mContext, R.layout.fragment_vip, null);
		x.view().inject(this, mView);
		init();
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		return mView;
	}

	@Override
	public void onResume() {
		if(shouldReloadData) {
			shouldReloadData = false;
			getData();
		}
		super.onResume();
	}

	private void init() {
		type = getArguments().getInt("type");
		organizaModel = (OrganizaModel) getArguments().getSerializable("organizaModel");
		if(organizaModel != null)
			companyId = organizaModel.getCompanyId();
		screenWidth = getResources().getDisplayMetrics().widthPixels;

		vipRv.setHasFixedSize(true);
		vipRv.setLayoutManager(new LinearLayoutManager(mContext));
		vipRv.addItemDecoration(new JpDiver(mContext));
		adapter = new VipInfoAdapter(mContext, new ArrayList<VipInfoModel.PrivilegeListBean>());
		vipRv.setAdapter(adapter);

		cachePath = mContext.getCacheDir() + "/vipInfo_" + type + "_" + companyId + ".dat";
		cacheManager = new FileCacheManager();
		adapter.setOnBtnClickListener(new VipInfoAdapter.OnBtnClickListener() {
			@Override
			public void onBtnClick(int row, int column) {
				if(!jpApplication.isLogin()){
					shouldReloadData = true;
					startActivity(new Intent(mContext, LoginActivity.class));
					return;
				}
				if(column == 0)
					return;
				VipInfoModel.PrivilegeListBean.ListBean data = adapter.getData(row).getList().get(column-1);
				String gradesId = data.getGradesId();
				String itemInfo = data.getInfo();
				String itemTitle = vipInfoModel.getPrivilegeTitle().get(column).getTitle();
				if("认领".equals(data.getInfo())) {
					shouldReloadData = true;
					startActivity(new Intent(mContext, JoinOrgnazitionAcitivity.class)
							.putExtra("company", organizaModel));
				} else {
					Intent intent = new Intent(mContext, VipBuyActivity.class)
							.putExtra("title", itemInfo + itemTitle)
							.putExtra("gradesId", gradesId);
					if ("升级".equals(data.getInfo())) {
						upgradeDialog.setTag(intent);
						upgradeDialog.show();
					} else {
						shouldReloadData = true;
						startActivity(intent);
					}
				}
			}
		});

		upgradeDialog = new CommDialog(mContext);
		upgradeDialog.setContent("升级后，系统会将你的VIP会员剩余有效期时间自动换成对等价值的VIP超级会员的天数进行累加");
		upgradeDialog.setLeft("取消");
		upgradeDialog.setRight("我要升级");
		upgradeDialog.setRightListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				shouldReloadData = true;
				startActivity((Intent) upgradeDialog.getTag());
			}
		});

		readCache();
	}


	private void readCache(){
		Observable.create(new Observable.OnSubscribe<VipInfoModel>() {
			@Override
			public void call(Subscriber<? super VipInfoModel> subscriber) {
				VipInfoModel data = (VipInfoModel) cacheManager.readObject(cachePath);
				subscriber.onNext(data);
			}
		}).subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Subscriber<VipInfoModel>() {
					@Override
					public void onCompleted() {
						getData();
					}
					@Override
					public void onError(Throwable e) {
						onCompleted();
					}
					@Override
					public void onNext(VipInfoModel data) {
						if(data != null) {
							vipInfoModel = data;
							setView(vipInfoModel);
						}
						onCompleted();
					}
				});
	}

	private void getData() {
		JsonObject param = new JsonObject();
		if(type == 1){
			param.addProperty("type", type);
			param.addProperty("id", companyId);
		}
		HttpHelper.getInstance(mContext).getVipInfo(param, 0x01, new ResultSubscriber.OnResultListener() {
			@Override
			public void onStart(int requestType) {}
			@Override
			public void onCompleted(int requestType) {}
			@Override
			public void onError(int requestType) {}
			@Override
			public void onNext(IModel data, int requestType) {
				vipInfoModel = data.getEntity(VipInfoModel.class);
				setView(vipInfoModel);

				new Thread(new Runnable() {
					@Override
					public void run() {
						cacheManager.wirteObject(vipInfoModel, cachePath);
					}
				}).start();
			}
		});
	}

	private void setView(VipInfoModel vipInfoModel){
		if(vipInfoModel == null)
			return;
		vipLevel.setText(vipInfoModel.getGradeName());

		if(vipInfoModel.getIsVip() == 1){
			vipDesc.setText("有效期至" + vipInfoModel.getVipTime());
			vipTime.setText("（还有" + vipInfoModel.getVipDays() + "天到期）");
			vipDesc.setTextColor(mContext.getResources().getColor(R.color.white));
			vipDesc.setVisibility(View.VISIBLE);
		} else if(vipInfoModel.getIsVip() == 2){
			vipDesc.setText("已过期");
			vipDesc.setTextColor(mContext.getResources().getColor(R.color.google_red));
			vipTime.setText("");
		} else{
			vipDesc.setText("享受更多服务请购买VIP" + (type==1 ? "企业" : "会员"));
			vipDesc.setTextColor(mContext.getResources().getColor(R.color.white));
			vipTime.setText("");
		}

		int columnCount = vipInfoModel.getPrivilegeTitle().size();
		if(columnCount <= 4)
			contentView.setMinimumWidth(screenWidth);
		else
			contentView.setMinimumWidth((int) (screenWidth/3.5*columnCount));

		vipTitle.removeAllViews();
		for(VipInfoModel.PrivilegeTitleBean titleBean : vipInfoModel.getPrivilegeTitle())
			if(titleBean == null)
				vipTitle.addView(getTitleView(null, null, null));
			else
				vipTitle.addView(getTitleView(titleBean.getTitle(), titleBean.getColor(), titleBean.getIcon()));
		adapter.updateAdapter(vipInfoModel.getPrivilegeList());
		vipRv.postDelayed(new Runnable() {
			@Override
			public void run() {
				adapter.notifyDataSetChanged();
			}
		}, 100);
	}

	private View getTitleView(String text, String textColor, String icon){
		View view = View.inflate(mContext, R.layout.item_vip_info, null);
		view.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
		TextView vipInfoTv = (TextView) view.findViewById(R.id.vip_info_tv);
		ImageView vipInfoIv = (ImageView) view.findViewById(R.id.vip_info_iv);
		if(TextUtils.isEmpty(text)){
			vipInfoTv.setVisibility(View.GONE);
		} else{
			vipInfoTv.setVisibility(View.VISIBLE);
			vipInfoTv.setText(text);
			try{
				vipInfoTv.setTextColor(Color.parseColor(textColor));
			} catch (Exception e){
				vipInfoTv.setTextColor(mContext.getResources().getColor(R.color.font_gray));
			}
		}
		if(TextUtils.isEmpty(icon)){
			vipInfoIv.setVisibility(View.GONE);
		} else{
			vipInfoIv.setVisibility(View.VISIBLE);
			ImageLoadUtil.load(mContext, icon, vipInfoIv);
		}
		return view;
	}
}
